const jwt = require('jsonwebtoken')

// 生成token
function generateToken(username, secretKey) {
  const token = jwt.sign({ username: username }, secretKey)
  return token
}

// 生成随机密钥
function generateRandomKey(length) {
  let key = ''
  const characters =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  const charactersLength = characters.length

  for (let i = 0; i < length; i++) {
    key += characters.charAt(Math.floor(Math.random() * charactersLength))
  }
  return key
}

const secretKey = 'secretKey'

// 验证token
function verifyToken(token) {
  return jwt.verify(token, secretKey, (err, decoded) => {
    if (err) {
      console.log(err)
      return {
        code: 404,
        msg: `token无效`,
      }
    }
    return {
      code: 200,
      username: decoded.username,
      msg: '获取用户名成功',
    }
  })
}

module.exports = {
  verifyToken,
  generateToken,
  generateRandomKey,
}
